package com.devops.admin.service.impl;


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.devops.admin.model.DOSResource;
import com.devops.admin.service.DOSDatasourceService;
import com.devops.admin.service.DOSResourceService;
import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @author hyb22
 * @version 1.0.0
 * @description TODO
 * @date 2022/10/18 16:21
 */
@Service
public class DOSDatasourceServiceImpl implements DOSDatasourceService {

    @Autowired
    private DOSResourceService dosResourceService;
    @Autowired
    DataSource dataSource;

    @Override
    public boolean checkDB(String dbName) {
        if (dataSource instanceof DynamicRoutingDataSource) {
            DynamicRoutingDataSource  dynamicRoutingDataSource =  (DynamicRoutingDataSource) dataSource;
            if (dynamicRoutingDataSource.getDataSources().containsKey(dbName)) {
                return true;
            } else {
                DOSResource resource = dosResourceService.getOne(Wrappers.<DOSResource>lambdaQuery().eq(DOSResource::getType,1).eq(DOSResource::getName,dbName));
                if (resource != null && resource.getId() != null && resource.getId() > 0) {
                    DruidDataSource druidDataSource = new DruidDataSource();
                    druidDataSource.setUrl(resource.getUrl());
                    druidDataSource.setUsername(resource.getUsers());
                    druidDataSource.setPassword(resource.getPassword());
                    druidDataSource.setDriverClassName(resource.getDriverName());
                    if (!dynamicRoutingDataSource.getDataSources().containsKey(dbName)) {
                        dynamicRoutingDataSource.addDataSource(dbName,druidDataSource);
                    }
                    return true;
                }
            }
        }
        return false;
    }
}
